package com.gjzhao.fmmall.websocket;

import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 创建websocket服务器
 */
@Component
@ServerEndpoint("/webSocket/{orderId}")
public class WebSocketServer {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 前端发送请求建立 websocket 连接，就会执行@OnOpen方法
     * - 说明：@PathParam 注解由websocket提供，用于专门获取前端携带过来的参数
     *
     * @param orderId
     * @param session
     */
    @OnOpen
    public void open(@PathParam("orderId") String orderId,
                     Session session) {
        logger.info("-----当前订单:" + orderId + ",已建立WebSocket连接------");
        sessionMap.put(orderId, session);
    }


    /**
     * 前端关闭页面或者主动关闭websocket连接，都会执行close
     *
     * @param orderId
     */
    @OnClose
    public void close(@PathParam("orderId") String orderId) {

        logger.info("-----当前订单:" + orderId + ",已关闭WebSocket连接------");

        sessionMap.remove(orderId);
    }


    /**
     * 调用逻辑
     *
     * @param orderId 订单id
     * @param msg     发送给前端的消息
     */
    public static void sendMsg(String orderId, String msg) {

        try {
            Session session = sessionMap.get(orderId);
            session.getBasicRemote().sendText(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
